package com.hserver.docker.event;

import com.hserver.docker.bean.Deploy;
import com.hserver.docker.bean.Record;
import com.hserver.docker.dao.RecordMapper;
import com.hserver.docker.service.*;
import com.hserver.docker.utils.DateUtils;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.queue.QueueHandler;
import top.hserver.core.ioc.annotation.queue.QueueListener;

/**
 * 部署是一个延时过程，此时还是走这个队列比较好
 */
@QueueListener(queueName = "deploy")
public class DeployEvent {


    @Autowired
    private GitService gitService;

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private DockerService dockerService;

    @Autowired
    private LogService logService;

    @Autowired
    private DeployService deployService;

    @QueueHandler(size = 5)
    public void deploy(String uuid,String id) {
        try {
            Record record = new Record();
            record.setUuid(uuid);
            record.setId(id);
            record.setStatus("拉取代码");
            record.setStartTime(DateUtils.getNow());
            recordMapper.insert(record);
            Deploy deploy = deployService.getDeploy(uuid);
            if (gitService.cloneProject(deploy, id)) {
                recordMapper.updateStatus("Docker构建中", id);
                if (dockerService.buildImage(deploy, id)) {
                    recordMapper.updateStatus("Docker构建完成", id);
                    if (dockerService.createContainer(uuid, id)) {
                        recordMapper.updateStatus("Docker 容器创建完成", id);
                        if (dockerService.runContainer(uuid, id)) {
                            recordMapper.updateStatus("部署完成", DateUtils.getNow(), id);
                        } else {
                            recordMapper.updateStatus("容器运行失败", DateUtils.getNow(), id);
                        }
                    } else {
                        recordMapper.updateStatus("Docker 容器创建失败", DateUtils.getNow(), id);
                    }
                } else {
                    recordMapper.updateStatus("Docker构建失败", DateUtils.getNow(), id);
                }
            } else {
                recordMapper.updateStatus("构建失败", DateUtils.getNow(), id);
            }
        } catch (Exception ignored) {
        }
    }
}
